<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-select v-model="filter_category" placeholder="请选择类别" style="width: 120px">
            <el-option value="" label="全部" />
            <el-option v-for="item in categorys" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            style="max-width: 600px"
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            v-if="combines.length"
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleCombine"
          >合并
          </el-button>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '新建报价单')"
          >新建目录册
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @cell-mouse-enter="(m) => m.active=true"
          @cell-mouse-leave="(m) => m.active=false"
          @sort-change="handleSort"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column align="center" width="120" prop="category" label="类别" sortable="custom">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.category"
                placeholder="选择类别"
                size="mini"
                style="width: 100%"
                @change="handleCategoryChange(scope.row)"
              >
                <el-option value="" label="未分类" />
                <el-option
                  v-for="item in categorys"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="feature_image" label="缩略图">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="产品图片预览"
                width="400"
                trigger="hover"
                :disabled="!getAllProductImages(scope.row).length"
                popper-class="image-preview-popover"
              >
                <div class="image-preview-grid">
                  <div
                    v-for="(image, index) in getAllProductImages(scope.row)"
                    :key="index"
                    class="preview-image-item"
                  >
                    <el-image
                      :src="image"
                      fit="cover"
                      style="width: 80px; height: 80px"
                      :preview-src-list="getAllProductImages(scope.row)"
                      :initial-index="index"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" />
                      </div>
                    </el-image>
                  </div>
                </div>
                <div v-if="!getAllProductImages(scope.row).length" class="no-images">
                  暂无图片
                </div>
                <el-image
                  slot="reference"
                  :src="scope.row.feature_image"
                  style="width: 100px; cursor: pointer"
                  fit="cover"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="token" label="token" width="400">
            <template slot-scope="scope">
              <div style="font-size: 12px; line-height: 1.4;">
                <div style="margin-bottom: 3px;">
                  <span style="color: #606266; font-size: 11px;">token:</span>
                  <a
                    :href="scope.row.quote_domain + scope.row.token"
                    title="打开报价单"
                    target="_blank"
                    style="color: #409EFF; text-decoration: none; font-weight: 500;"
                  >
                    {{ scope.row.token }}
                  </a>
                </div>
                <div style="margin-bottom: 3px;">
                  <span style="color: #606266; font-size: 11px;">客户看名称:</span>
                  <a
                    :href="scope.row.quote_domain + scope.row.token"
                    title="打开报价单"
                    target="_blank"
                    style="color: #409EFF; text-decoration: none; font-weight: 500;"
                  >
                    {{ scope.row.name }}
                  </a>
                </div>
                <div v-if="scope.row.note" style="margin-top: 4px;">
                  <span style="color: #E6A23C; font-weight: bold; font-size: 11px;">备注:</span>
                  <span style="color: #E6A23C; font-weight: 500;">{{ scope.row.note }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="详细信息" width="200">
            <template slot-scope="scope">
              <div style="line-height: 1.4; font-size: 12px;">
                <div style="margin-bottom: 2px;">
                  <strong>数量:</strong>
                  <span style="cursor: pointer; color: #409EFF;" @click="handleShowProduct(scope.row)">
                    {{ scope.row.total_products }}
                  </span>
                </div>
                <div v-if="scope.row.phone" style="margin-bottom: 2px;">
                  <strong>电话:</strong> {{ scope.row.phone }}
                </div>
                <div v-if="scope.row.email" style="margin-bottom: 2px;">
                  <strong>邮箱:</strong> {{ scope.row.email }}
                </div>
                <div v-if="scope.row.create_at">
                  <strong>创建:</strong>
                  <span style="color: #909399; font-size: 11px;">{{ scope.row.create_at }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="product_page_generated" label="网页状态" width="200" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.product_page_generated"
                :active-value="true"
                :inactive-value="false"
                active-text="已生成"
                inactive-text="未生成"
                :disabled="listLoading"
                @change="handlePageStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="320">
            <template slot-scope="scope">
              <el-tooltip content="生成产品网页" placement="top">
                <ProductPageGenerator
                  :images="getProductImages(scope.row)"
                  :product-name="scope.row.name"
                  button-text=""
                  :button-type="scope.row.page_generated ? 'success' : 'warning'"
                  button-size="mini"
                  button-icon="el-icon-magic-stick"
                  @generated="(result) => handlePageGenerated(result, scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="生成目录册图片" placement="top">
                <CatalogImageGenerator
                  :quote-id="scope.row.id"
                  :images="getAllProductImages(scope.row)"
                  button-text=""
                  button-size="mini"
                  button-icon="el-icon-picture-outline"
                  @generated="(result) => handleCatalogGenerated(result, scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="生成代码" placement="top">
                <el-button type="primary" size="mini" icon="el-icon-document-copy" circle @click="handlegeneratedCode(scope.row)" />
              </el-tooltip>
              <el-tooltip content="获取所有图片链接" placement="top">
                <el-button type="info" size="mini" icon="el-icon-link" circle @click="handleGetAllImageLinks(scope.row)" />
              </el-tooltip>
              <el-tooltip content="复制当前目录册" placement="top">
                <el-button size="mini" type="primary" icon="el-icon-copy-document" circle @click="handleAction('copy', scope.row)" />
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button size="mini" type="success" icon="el-icon-edit" circle @click="handleAction('edit', scope.row)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleAction('delete', scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <!-- 代码显示对话框 -->
    <el-dialog
      title="生成的代码"
      :visible.sync="showCodeDialog"
      width="60%"
      @close="showCodeDialog = false"
    >
      <el-input
        v-model="generatedCode"
        type="textarea"
        :rows="20"
        readonly
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showCodeDialog = false">关闭</el-button>
      </span>
    </el-dialog>
    <crmquoteproduct :quote="quote" :is-new="isNew" :selected-products="products" :visible="showProductVisible" @close="showProductVisible=false" />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmquote'
import qs from 'qs'
import { countries, customer_source, getCountryLabel } from '../../api/crm/crmcommon'
import Crmquoteproduct from './elements/crmquoteproduct'
import ProductPageGenerator from '@/components/ProductPageGenerator'
import CatalogImageGenerator from '@/components/CatalogImageGenerator'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmcustomer',
  components: { Crmquoteproduct, ProductPageGenerator, CatalogImageGenerator },
  data() {
    return {
      showCodeDialog: false,
      generatedCode: '',
      combines: [],
      data: [],
      filter_category: '',
      categorys: [
        {
          label: '跑步',
          value: 'running'
        },
        {
          label: '健身',
          value: 'fitness'
        },
        {
          label: '瑜伽',
          value: 'yoga'
        },
        {
          label: '骑行',
          value: 'cycling'
        },
        {
          label: '钓鱼',
          value: 'fishing'
        },
        {
          label: '马术',
          value: 'equestrian'
        },
        {
          label: '篮球',
          value: 'basketball'
        },
        {
          label: '足球',
          value: 'football'
        },
        {
          label: '羽毛球',
          value: 'badminton'
        },
        {
          label: '游泳',
          value: 'swimming'
        },
        {
          label: '户外',
          value: 'outdoor'
        },
        {
          label: '其他',
          value: 'other'
        }
      ],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      customer_sources: customer_source,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      products: [],
      showProductVisible: false,
      quote: {},
      isNew: false,
      temp: {
        name: '',
        note: '',
        products: []
      },

      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    resetTemp() {
      this.temp = {
        name: '' // 供应商名称
      }
    },
    handleShowProduct(row) {
      this.products = row.products ? row.products : []
      this.quote_id = row.id
      this.showProductVisible = true
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        category: this.filter_category,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    showUrl(row) {
      console.log(row.token)
    },
    handleCombine() {
      if (this.combines.length < 2) {
        this.$notify({
          title: '错误',
          message: '请至少选择两个报价单',
          type: 'error',
          duration: 2000
        })
        return
      }
      // 只提取combins的id列表
      Put(this.combines[0].id, { task: 'combine', ids: this.combines.map(v => v.id) }).then((response) => {
        this.innerDialogVisible = false
        this.getList()
        this.notify('复制')
      })
    },
    handlegeneratedCode(row) {
      const imageUrl = row.feature_image
      if (!imageUrl) {
        this.$message({
          message: '没有可用的图片生成代码',
          type: 'error'
        })
        return
      }
      this.generatedCode = `
        <a href="https://quote.berunwear.com/${row.token}" target="_blank" style="display: block; text-align: center;">
          <img
            src="${imageUrl}"
            class="d-block w-100 product-image"
            alt="xon1q6li"
            loading="lazy"
            style="display: block; margin: 0 auto; height: 400px; object-fit: cover;">
          <h3 style="margin: 10px 0; color: #000; text-decoration: none;">${row.name}</h3>
        </a>`
      this.showCodeDialog = true
      // 复制到剪切板
      this.$copyText(this.generatedCode).then(() => {
        this.$message({
          message: '代码已复制到剪切板',
          type: 'success'
        })
      }, () => {
        this.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    // 获取所有图片链接
    handleGetAllImageLinks(row) {
      const images = this.getAllProductImages(row)
      if (!images || images.length === 0) {
        this.$message({
          message: '该目录册没有图片',
          type: 'warning'
        })
        return
      }

      // 一行一个图片链接
      const imageLinks = images.join('\n')

      // 复制到剪贴板
      this.$copyText(imageLinks).then(() => {
        this.$message({
          message: `已复制 ${images.length} 个图片链接到剪贴板`,
          type: 'success'
        })
      }, () => {
        this.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.resetTemp()
          this.quote = {}
          this.isNew = true
          this.products = []
          this.showProductVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除客户:${row.name}?`
          this.temp = Object.assign({}, row)
          this.confirm()
          break
        case 'copy':
          Put(row.id, { task: 'copy' }).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('复制')
          })
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改客户:${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.isNew = false
          this.quote = row
          this.products = row.products
          this.showProductVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSelectionChange(val) {
      this.combines = val
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    // 获取产品图片列表
    getProductImages(row) {
      const images = []

      // 添加缩略图
      if (row.feature_image) {
        images.push(row.feature_image)
      }

      // 从products中获取更多图片
      if (row.products && Array.isArray(row.products)) {
        row.products.forEach(product => {
          if (product.image && !images.includes(product.image)) {
            images.push(product.image)
          }
          if (product.images && Array.isArray(product.images)) {
            product.images.forEach(img => {
              if (img && !images.includes(img)) {
                images.push(img)
              }
            })
          }
        })
      }

      // 如果没有图片，返回空数组
      return images.length > 0 ? images : []
    },
    // 获取该报价单下所有产品的所有图片（用于悬停预览）
    getAllProductImages(row) {
      const images = []

      // 从products中获取所有图片
      if (row.products && Array.isArray(row.products)) {
        row.products.forEach(product => {
          if (product.images && Array.isArray(product.images)) {
            product.images.forEach(img => {
              if (img && !images.includes(img)) {
                images.push(img)
              }
            })
          }
        })
      }

      // 如果没有产品图片，则添加缩略图作为备选
      if (images.length === 0 && row.feature_image) {
        images.push(row.feature_image)
      }

      return images
    },
    // 处理网页生成结果
    handlePageGenerated(result, row) {
      this.$message.success('网页生成完成')
      console.log('生成结果:', result)
      // 标记该行已生成网页
      this.$set(row, 'page_generated', true)
      // 这里可以根据需要处理生成结果，比如显示在对话框中或者跳转到新页面
    },
    // 处理目录册图片生成结果
    handleCatalogGenerated(result, row) {
      this.$message.success('目录册图片生成任务已创建，正在后台处理中')
      console.log('目录册生成结果:', result)

      // 提示用户任务正在处理
      this.$notify({
        title: '任务创建成功',
        message: `目录册图片正在生成中，请稍后刷新查看结果。任务ID: ${result.id}`,
        type: 'success',
        duration: 5000
      })

      // 可以在这里刷新列表或显示生成的图片
      // this.getList()
    },
    // 处理网页状态开关变化
    handlePageStatusChange(row) {
      this.listLoading = true
      const status = row.product_page_generated
      const statusText = status === true ? '已生成' : '未生成'

      Put(row.id, { product_page_generated: status }).then((response) => {
        this.listLoading = false
        this.$message.success('网页状态已更新为: ' + statusText)
      }).catch(err => {
        this.listLoading = false
        // 如果更新失败，恢复原来的状态
        row.product_page_generated = !status
        this.$message.error('更新失败: ' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
      })
    },
    // 处理类别变更
    handleCategoryChange(row) {
      const originalCategory = row.category
      const categoryLabel = this.getCategoryLabel(row.category)

      Put(row.id, { category: row.category }).then((response) => {
        this.$message.success(`类别已更新为: ${categoryLabel || '未分类'}`)
      }).catch(err => {
        // 如果更新失败，恢复原来的类别
        row.category = originalCategory
        const errorMsg = err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message
        this.$message.error('类别更新失败: ' + errorMsg)
      })
    },
    // 获取类别标签
    getCategoryLabel(value) {
      if (!value) return '未分类'
      const category = this.categorys.find(item => item.value === value)
      return category ? category.label : value
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

/* 图片预览相关样式 */
.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.preview-image-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 18px;
}

.no-images {
  text-align: center;
  color: #909399;
  padding: 20px;
}

/* 自定义 popover 样式 */
.image-preview-popover {
  padding: 12px !important;
}

.image-preview-popover .el-popover__title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #303133;
}
</style>
